package com.guguskins.back.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guguskins.back.common.exception.GlobalException;
import com.guguskins.back.entity.GuAdminRole;
import com.guguskins.back.entity.GuAdminUser;
import com.guguskins.back.entity.vo.PageVo;
import com.guguskins.back.mapper.GuAdminUserMapper;
import com.guguskins.back.service.GuAdminRoleService;
import com.guguskins.back.service.GuAdminUserService;
import com.guguskins.back.utils.MessageMD5;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author mybatis-plus
 * @since 2021-07-16
 */
@Service
public class GuAdminUserServiceImpl extends ServiceImpl<GuAdminUserMapper, GuAdminUser> implements GuAdminUserService {
    private final static Logger logger = LogManager.getLogger(GuAdminUser.class);
    @Autowired
    private GuAdminUserMapper adminUserMapper;
    @Autowired
    private GuAdminRoleService adminRoleService;




    @Override
    public GuAdminUser findByName(String userName) {
        LambdaQueryWrapper<GuAdminUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(GuAdminUser::getUsername, userName);

        return adminUserMapper.selectOne(queryWrapper);
    }

    @Override
    public GuAdminUser selectByUsername(String username) {
        LambdaQueryWrapper<GuAdminUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(GuAdminUser::getUsername, username);

        return adminUserMapper.selectOne(queryWrapper);
    }

    @Override
    public int add(GuAdminUser adminUser) {

        int count = adminUserMapper.selectCount(new QueryWrapper<GuAdminUser>() {
            {
                eq("username", adminUser.getUsername());
            }
        });
        if (count > 0) {
            throw new GlobalException("用户名已存在");
        }
        adminUser.setPassword(MessageMD5.MD5(adminUser.getPassword()));

        int result = adminUserMapper.insert(adminUser);
        if (!ObjectUtils.isEmpty(adminUser.getRoleId())) {
            GuAdminRole adminRoleEntity = new GuAdminRole();
            adminRoleEntity.setAdminId(adminUser.getId());
            adminRoleEntity.setRoleId(adminUser.getRoleId());
            adminRoleService.save(adminRoleEntity);
        }
        return result;
    }

    @Override
    public int edit(GuAdminUser adminUser) {

        int count = adminUserMapper.selectCount(new QueryWrapper<GuAdminUser>() {
            {
                eq("username", adminUser.getUsername());
                ne("id", adminUser.getId());
            }
        });
        if (count > 0) {
            throw new GlobalException("用户名已存在");
        }

        GuAdminUser adminUserEntity = adminUserMapper.selectById(adminUser.getId());
        if ("admin".equals(adminUserEntity.getUsername()) && !"admin".equals(adminUser.getUsername())) {
            throw new GlobalException("admin不允许修改用户名");
        }


        //修改用户角色
        if (!ObjectUtils.isEmpty(adminUser.getRoleId())) {
            GuAdminRole adminRoleEntity = adminRoleService.getOne(new QueryWrapper<GuAdminRole>() {
                {
                    eq("admin_id", adminUser.getId());
                }
            });

            if (adminRoleEntity == null) {
                adminRoleEntity = new GuAdminRole();
                adminRoleEntity.setId(adminUser.getId());
                adminRoleEntity.setRoleId(adminUser.getRoleId());
                adminRoleService.save(adminRoleEntity);
            } else {
                adminRoleEntity.setRoleId(adminUser.getRoleId());
                adminRoleService.updateById(adminRoleEntity);
            }
        }
        if (!ObjectUtils.isEmpty(adminUser.getPassword())) {
            adminUser.setPassword(MessageMD5.MD5(adminUser.getPassword()));
        } else {
            adminUser.setPassword(null);
        }
        return adminUserMapper.updateById(adminUser);
    }

    @Override
    public boolean changeRole(Integer adminId, Integer roleId) {

        GuAdminRole adminRole = adminRoleService.getOne(new QueryWrapper<GuAdminRole>() {
            {
                eq("admin_id", adminId);
                last("limit 1");
            }
        });
        boolean result = false;
        if (adminRole != null) {
            adminRole.setRoleId(roleId);
            result = adminRoleService.updateById(adminRole);
        } else {
            adminRole = new GuAdminRole();
            adminRole.setAdminId(adminId);
            adminRole.setRoleId(roleId);
            result = adminRoleService.save(adminRole);
        }
        return result;
    }

    @Override
    public int updateStatus(Integer[] ids, int status) {
        AtomicInteger count = new AtomicInteger();
        List<Integer> collect = Stream.of(ids).collect(Collectors.toList());
        List<GuAdminUser> adminUsers = adminUserMapper.selectBatchIds(collect);
        adminUsers.forEach(adminUser -> {

            adminUser.setStatus(status);
            int result = adminUserMapper.updateById(adminUser);
            count.addAndGet(result);
            if (result <= 0) {
                logger.error("用户{}，{}失败", adminUser.getId(), status == 1 ? "启用" : "禁用");
            }
        });
        return count.get();
    }

    @Override
    public PageVo<GuAdminUser> getPage(int p, int size, String username) {

        int index = (p - 1) * size;
        List<GuAdminUser> adminUserEntityList = adminUserMapper.getPage(index, size, username);
        Integer count = adminUserMapper.selectCount(new QueryWrapper<GuAdminUser>() {
            {
                like(!ObjectUtils.isEmpty(username), "username", username);
            }
        });
        return new PageVo<>(adminUserEntityList, count);
    }

    @Override
    public GuAdminUser getDetail(Integer id) {

        return null;
    }

    @Override
    public boolean isSysAdmin(Integer userId) {
        GuAdminUser admin = this.getById(userId);
        return ObjectUtils.isEmpty(admin) || "admin".equals(admin.getUsername());
    }

    @Override
    public int changePassword(GuAdminUser adminUser) {
        GuAdminUser adminUserEntity = adminUserMapper.selectOne(new QueryWrapper<GuAdminUser>() {
            {
                eq("username", adminUser.getUsername());
                last("limit 1");
            }
        });

        if (adminUserEntity == null) {
            throw new GlobalException("未知用户名！");
        }
        if (!ObjectUtils.isEmpty(adminUser.getPassword())) {
            adminUserEntity.setPassword(MessageMD5.MD5(adminUser.getPassword()));
        } else {
            adminUserEntity.setPassword(null);
        }
        return adminUserMapper.updateById(adminUserEntity);
    }
}

